#-------------------------------------------------------------------------------
# Name:       odp2script.py
# Purpose:    Extract notes and image sequences from presentation files and
#             create a "script" data structure in a dict
#
# Authors:    Glenn Ramsey <glenn.ramsey@slidespeech.com>
#
# Copyright:  (c) Slidespeech Ltd 2012
# Licence:    MIT license
#-------------------------------------------------------------------------------

import os, sys
from zipfile import ZipFile
from xml.sax import make_parser, handler
#import glob

class NoteHandler(handler.ContentHandler):
    """A ContentHandler to extract the text from <presentation:notes> elements"""
    def __init__(self):
        self.noteText = ""
        self.noteList = []
        self.inNotesElement = 0

    def startElement(self, name, attrs):        
        if "presentation:notes"==name:
            self.inNotesElement = 1
            
    def characters(self, ch):
        if self.inNotesElement:
            self.noteText = self.noteText + ' ' + ch
        
    def endElement(self, name, ):
        if "presentation:notes"==name:
            self.inNotesElement = 0
            self.noteList.append(self.noteText)
            self.noteText = ""


def extractNotes(odpFile):
    """Extracts text from <presentation:notes> element in the given file.
    Returns a list with the notes from each element as a separate item."""
    parser = make_parser()
    handler = NoteHandler()
    parser.setContentHandler(handler)
    try:
        #baseName = filename.replace(".odp","")
        odp = ZipFile(odpFile,'r')
        f = odp.open(u"content.xml")
        parser.parse(f)
        f.close()
        
        if __debug__: # won't execute if Python is run with the -O flag
            print "Notes found in doc:"
            for note in handler.noteList:
                print note
            
        return handler.noteList
            
    except Exception as ex:
        # FIXME: record exception details
        raise ex


#def extractPNG(odpFile, imageDir):
#    try:
#        # create .png files
#        # PyUno has to be correctly installed for this to work
#        args = [odpFile]
#        odp2png.runparseNoOpts(args, tempDir=imageDir)
#    except:
#        # FIXME record exception details
#        raise


#def createScript(notesList): #, imageDir):
#
#    # shouldn't be any need to check for an upper case extension
#    imageFileList = glob.glob(os.path.join(imageDir, "*.png"))
#    
#    # check that we have the same number of images as notes
#    if len(imageFileList) != len(notesList):
#        e = Exception("Number of images and speaker notes is different")
#        raise e
#           
#    s = {}
#    # the top level is a Sequence
#    seq = []
#    for i in range(len(notesList)):
#        q = {}
#        q['t'] = "Slide{0}".format(i)
#        q['l'] = "en"
#        q['q'] = notesList[i]
#        # absolute path of image file
#        q['i'] = imageFileList[i]
#        seq.append(q)
#    s['S'] = seq
#    
#    return s


#if __name__ == "__main__":
#    # a simple test/demo
#    odpFile = sys.argv[1]
#    notes = extractNotes(odpFile)
#    imageDir = odpFile + "_png"
#    try:
#        os.makedirs(imageDir)
#    except OSError:
#        # dir already exists
#        pass
#    
#    renderToPNG(odpFile, imageDir)
#    
#    s = createScript(notes, imageDir)
#    
#    import json
#    print json.dumps(s, indent = 2)
    
    
    
 